<?php

namespace App\Admin\Controllers;

use App\Models\Squad;
use App\Models\Student;
use App\Models\Class_type;
use App\Models\Class_section_group;
use App\Models\Campus;
use App\Admin\Extensions\Tools\ChangeSquad;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Show;
use Illuminate\Http\Request;
use App\Admin\Extensions\ExcelExpoter;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\DB;
use  App\Admin\Controllers\Common\ReportBase;

class My_squadController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header(trans('admin.my_squad'))
            ->description(trans('admin.list'))
            ->body($this->grid());
    }

    public function show($id, Content $content)
    {
        return $content
            ->header(trans('admin.my_squad'))
            ->description(trans('admin.detail'))
            ->body(Admin::show(Squad::findOrFail($id), function (Show $show) {
                $show->panel()->tools(function ($tools){
                    $tools->disableDelete();
                    $tools->disableEdit();
                    $tools->disableList();
                });
                $show->classtype()->name('班型');
                $show->no('班号')->name();
                $show->classsection()->name('班段');
                $show->classgroup()->name('分组');

                $show->students('学生列表', function ($line) {
                    $line->model()->where('status','=','1');
                    $line->setResource('/admin/my_student');
                    //$line->id(trans('admin.ID'))->sortable();
                    $line->no(trans('admin.student_no'))->sortable();
                    $line->ch_name(trans('admin.ch_name'));
                    $line->en_name(trans('admin.en_name'));
                    $line->sex(trans('admin.sex'))->sortable()->editable('select',['1'=>'男','2'=>'女']);
                    $line->squad_id(trans('admin.squad_id'))->display(function($squad_id){
                        return Squad::find($squad_id)->name;
                    });
                    $line->column('听写')->display(function(){
                        return '<a href="/admin/student_detail?type=1&id='.$this->id.'">查看</a>';
                    });
                    $line->column('测验')->display(function(){
                        return '<a href="/admin/student_detail?type=2&id='.$this->id.'">查看</a>';
                    });
                    $line->column('考勤')->display(function(){
                        return '<a href="/admin/student_detail?type=3&id='.$this->id.'">查看</a>';
                    });
                    $line->column('家校')->display(function(){
                        return '<a href="/admin/student_detail?type=4&id='.$this->id.'">查看</a>';
                    });
                    $line->column('作业')->display(function(){
                        return '<a href="/admin/student_detail?type=5&id='.$this->id.'">查看</a>';
                    });
                    $line->column('报表')->display(function(){
                        return '<a href="/admin/student_report?id='.$this->id.'">查看</a>';
                    });
                    $line->column('转班')->display(function(){
                        return '<a onclick="trans('.$this->id.')">申请转班</a>';
                    });
                    $line->column('休/退学')->display(function(){
                        return '<a onclick="leaveFunc('.$this->id.')">申请休/退学</a>';
                    });

                    $line->grade('年级')->editable('select', [1 => '小班', 2 => '中班', 3 => '大班',4 => '一年级',
                        5 => '二年级',6 => '三年级',7 => '四年级',8 => '五年级',9 => '六年级',10 => '七年级',11 => '八年级',12 => '九年级',
                        13 => '高一',14 => '高二',15 => '高三']);
                    $line->school('学校')->editable();
                    $line->enrollment_time(trans('admin.enrollment_time'))->display(function (){
                            return date('Y/m/d',strtotime($this->enrollment_time));
                    })->sortable();
                    $line->disableActions();//禁用行操作
                    $line->disableCreateButton();//禁用创建按钮
                    //禁用批量删除
                    $line->tools(function ($tools) {
                        $tools->batch(function ($batch) {
                            $batch->disableDelete();
                        });
                    });
                    // $line->actions(function ($actions) {
                    //     $actions->prepend('<a href="/admin/attendance_entering/'.$actions->getKey().'" title="考勤录入"><i class="fa fa-futbol-o"></i></a>');
                    //     $actions->prepend('&nbsp;&nbsp;');
                    //     $actions->prepend('<a href="/admin/mark_entering/'.$actions->getKey().'" title="成绩录入"><i class="fa fa-map"></i></a>');
                    //     $actions->disableView();
                    // });
                    $filename="学生列表";
                    $line->exporter(new ExcelExpoter($line,$filename));

                    $line->filter(function ($filter) {
                        $filter->column(1/2, function ($filter) {
                            // 去掉默认的id过滤器
                            $filter->disableIdFilter();
                            $filter->like('no',trans('admin.student_no'));
                            $filter->like('en_name',trans('admin.en_name'));
                            $filter->between('enrollment_time', trans('admin.enrollment_time'))->datetime();
                        });
                        $filter->column(1/2, function ($filter) {
                            $filter->like('ch_name',trans('admin.ch_name'));
                            $filter->equal('sex', trans('admin.sex'))->select($options = ['1'=> trans('admin.men') , '2'=> trans('admin.women')]);
                            $filter->equal('status', trans('admin.status'))->select($options = ['1'=> trans('admin.zaidu') , '2'=> trans('admin.xiuxue'), '3'=> trans('admin.tuixue')]);
                        });
                    });
                });
        }))->body($this->jsscript());
    }
    /**
     * Make a grid builder.
     *
     * @return Grid
     */

    protected function grid()
    {
        $grid = new Grid(new Squad());

        $class_teacher = Admin::user()->id;
        $grid->model()->where('class_teacher', '=', $class_teacher);
        //$grid->id(trans('admin.ID'))->sortable();
        // $grid->type(trans('admin.type'))->display(function($type){
        //     if ($this->type==0) {
        //         return 'N/A';
        //     }else{
        //         return Class_type::find($this->type)->name;
        //     }
        // })->sortable();
        // $grid->no(trans('admin.no'))->sortable();
        $grid->name(trans('admin.name'))->sortable();
        $grid->section(trans('admin.section'))->display(function($section){
            if ($this->section==0) {
                return 'N/A';
            }else{
                return Class_section_group::find($this->section)->name;
            }
        })->sortable();
        $grid->group(trans('admin.group'))->display(function($group){
            if ($this->group==0) {
                return 'N/A';
            }else{
                return Class_section_group::find($this->group)->name;
            }
        })->sortable();


        $grid->campus(trans('admin.campus'))->display(function($campus){
            if ($this->campus==0) {
                return 'N/A';
            }else{
                return Campus::find($this->campus)->name;
            }
        })->sortable();

        $grid->class_teacher(trans('admin.class_teacher'))->display(function($class_teacher){
            if ($this->class_teacher==0) {
                return 'N/A';
            }else{
                return Admin::user()->find($this->class_teacher)->username;
            }
        })->sortable();
        $grid->column(trans('admin.start_class_detail'))->display(function () {
            if ($this->start_season==1) {
                return $this->start_year.'年'.trans('admin.spring').'-'.$this->batch;
            }elseif ($this->start_season==2) {
                return $this->start_year.'年'.trans('admin.autumn').'-'.$this->batch;
            }
        });
        $grid->column(trans('admin.start_class_date'))->display(function (){
                return date('Y/m/d',strtotime($this->start_date)).'—'.date('Y/m/d',strtotime($this->end_date));
        });
        $grid->study_jindu('教学进度')->style('max-width:600px;word-break:break-all;');
        $grid->column('人数')->display(function(){
            $num = Student::where('squad_id',$this->id)->where('status','1')->count();
            return '<a href="my_squad/'.$this->id.'" style="text-decoration:underline">'.$num.'</a>';
        });

        // $grid->study_jindu('教学进度');

        //禁用导出按钮
        $grid->disableExport();
        // $squad_name = Squad::find($id)->name();
        // $filename=$squad_name."学生列表";
        // $grid->exporter(new ExcelExpoter($grid,$filename));

        //禁用创建按钮
        $grid->disableCreateButton();

        $grid->disableActions();
/*        $grid->actions(function ($actions) {
            $actions->disableDelete();
            $actions->disableEdit();
            $actions->disableView();
        });*/
        $grid->tools(function ($tools) {
            //关闭批量删除
            $tools->batch(function ($batch) {
                $batch->disableDelete();
            });
        });


        $grid->filter(function (Grid\Filter $filter) {

            //$filter->expand();

            $filter->column(1/2, function ($filter) {
                $filter->disableIdFilter();
                $filter->equal('type', trans('admin.type'))->select(Class_type::all()->pluck('name', 'id'));
                $filter->equal('section', trans('admin.section'))->select(Class_section_group::where('pid','=','0')->get()->pluck('name', 'id'));
                $filter->equal('campus', trans('admin.campus'))->select(Campus::all()->pluck('name', 'id'));
                $filter->equal('start_year', trans('admin.start_year'))->year();

            });
            $filter->column(1/2, function ($filter) {
                $filter->equal('no',trans('admin.no'));
                $filter->equal('group', trans('admin.group'))->select(Class_section_group::where('pid','!=','0')->get()->pluck('name', 'id'));
                // $filter->equal('class_teacher', trans('admin.class_teacher'))->select(Admin::user()->where('type','=','1')->get()->pluck('name', 'id'));
                $filter->equal('start_season', trans('admin.start_season'))->radio([
                    ''   => trans('admin.all'),
                    '1'  => trans('admin.spring'),
                    '2'  => trans('admin.autumn'),
                ]);
                $filter->equal('batch',trans('admin.batch'));
            });
        });
        return $grid;
    }

    protected function jsscript(){
        return view('admin.apply');
    }

	public function report($id,Request $r){
		$year = isset($r['year']) ? $r['year'] : date("Y");
		$season = isset($r['season']) ? $r['season'] : "1";
		$reportBase = new ReportBase($year,$season);
		$week = $reportBase->getProtectedAttr()['week'];
		$opt_start = [];
		for($i=0;$i<$week;$i++){
			$opt_start[] = [
				'label' => "第".($i+1)."周",
				'value' => $i
			];
		}
		$opt_end = [];
		for($i=$week;$i>0;$i--){
			$opt_end[] = [
				'label' => "第".($i)."周",
				'value' => $i
			];
		}
		$default_week = [
			'start' => isset($r['week_s']) ? $r['week_s'] : $week-4,
			'end' => isset($r['week_e']) ? $r['week_e'] : $week-1
		];
		$time = $reportBase->getTimebyWeek($default_week['start']+1,$default_week['end']+1);
		// 班级信息
		$my_squad_ids = squad::where('class_teacher',Admin::user()->id)
			->pluck('id')->toArray();
		if(!in_array($id,$my_squad_ids)){
			return $this->redirectWithMsg("您无权查看该班级","admin","danger","Error");
		}
		$squad_info = DB::table("squads as s")
			->leftJoin("class_types as c",'s.type','=','c.id')
			->leftJoin("class_section_groups as g",'s.section','=','g.id')
			->leftJoin("campuses as u",'s.campus','=','u.id')
			->where("s.id",'=',$id)
			->first(['s.*','c.name as type_name','g.name as section_name','u.name as campus_name']);
		$squad_info = json_decode(json_encode($squad_info),true);
		if(!empty($squad_info)){
			$squad_info['group_name'] = DB::table("class_section_groups")
				->where('id','=',$squad_info['group'])
				->value("name");
		}
		// print_r($time);die;
		$st_ids = DB::table("students")->where('squad_id','=',$r['squad_id'])->pluck('id');
		$tx_time =DB::table('dictation_score_records')
			->whereIn('student_id',$st_ids)
			->where([
				['created_at','>',$time['s_date']." 00:00:00"],
				['created_at','<=',$time['e_date']." 00:00:00"],
			])->groupBy('created_at')->pluck('created_at');
		$tx_time = json_decode(json_encode($tx_time),true);
		$tx_count = sizeof($tx_time);
		$cs_time = DB::table('test_score_records')
			->whereIn('student_id',$st_ids)
			->where([
				['created_at','>',$time['s_date']." 00:00:00"],
				['created_at','<=',$time['e_date']." 00:00:00"],
			])->groupBy('created_at')->pluck('created_at');
		$cs_time = json_decode(json_encode($cs_time),true);
		$cs_count = sizeof($cs_time);
		$kq_time = DB::table('attendance_records')
			->whereIn('student_id',$st_ids)
			->where([
				['created_at','>',$time['s_date']." 00:00:00"],
				['created_at','<=',$time['e_date']." 00:00:00"],
			])->groupBy('created_at')->pluck('created_at');
		$kq_time = json_decode(json_encode($kq_time),true);
		$kq_count = sizeof($kq_time);
		$jx_time = DB::table('jiaxiao_records')
			->whereIn('student_id',$st_ids)
			->where([
				['created_at','>',$time['s_date']." 00:00:00"],
				['created_at','<=',$time['e_date']." 00:00:00"],
			])->groupBy('created_at')->pluck('created_at');
		$jx_time = json_decode(json_encode($jx_time),true);
		$jx_count = sizeof($jx_time);
		$zy_time = DB::table('zuoye_records')
			->whereIn('student_id',$st_ids)
			->where([
				['created_at','>',$time['s_date']." 00:00:00"],
				['created_at','<=',$time['e_date']." 00:00:00"],
			])->groupBy('created_at')->pluck('created_at');
		$zy_time = json_decode(json_encode($zy_time),true);
		$zy_count = sizeof($zy_time);
		return view("admin.my_squad_report",[
			"SquadInfo" => $squad_info,
			"Count" => [
				"tx" => $tx_count,
				"cs" => $cs_count,
				"kq" => $kq_count,
				"jx" => $jx_count,
				"zy" => $zy_count,
				"tx_time" => $tx_time,
				"cs_time" => $cs_time,
				"kq_time" => $kq_time,
				"jx_time" => $jx_time,
				"zy_time" => $zy_time
			],
			"OPT" => [
				"start" => $opt_start,
				"end" => $opt_end,
				"year" => $year,
				"season" => $season
			],
			"DefaultWeek" => $default_week
		]);
	}

	public function getReportData(Request $r) {
		$count_info = json_decode($r['count_info'],true);
		$rows = DB::table("students")->where('squad_id','=',$r['squad_id'])->get([
			'id','no','ch_name','en_name'
		]);
		$st_ids = DB::table("students")->where('squad_id','=',$r['squad_id'])->pluck('id');
		$rows = json_decode(json_encode($rows),true);
		// 听写
		$tx = DB::table('dictation_score_records')
			->whereIn("student_id",$st_ids)
			->get(['dictation_score','created_at','student_id']);
		$tx = json_decode(json_encode($tx),true);
		// 测试
		$cs = DB::table('test_score_records')
			->whereIn("student_id",$st_ids)
			->get(['test_score','created_at','student_id']);
		$cs = json_decode(json_encode($cs),true);
		// 考勤
		$kq = DB::table('attendance_records')
			->whereIn("student_id",$st_ids)
			->get(['attendance_status','created_at','student_id']);
		$kq = json_decode(json_encode($kq),true);
		// 家校
		$jx = DB::table('jiaxiao_records')
			->whereIn("student_id",$st_ids)
			->get(['jiaxiao_score','created_at','student_id']);
		$jx = json_decode(json_encode($jx),true);
		// 作业
		$zy = DB::table('zuoye_records')
			->whereIn("student_id",$st_ids)
			->get(['zuoye_score','created_at','student_id']);
		$zy = json_decode(json_encode($zy),true);
		foreach($kq as &$v){
			switch ($v['attendance_status']) {
				case '1':
					$v['attendance_status'] = "正常";
					break;
				case '2':
					$v['attendance_status'] = "请假";
					break;
				case '3':
					$v['attendance_status'] = "迟到";
					break;
				case '4':
					$v['attendance_status'] = "缺勤";
				case '5':
					$v['attendance_status'] = "家长代课";
					break;
			}
		}
		foreach($rows as &$v){
			for($i=0;$i<$count_info['tx'];$i++){
				$v['tx_'.$i] = "";
				foreach($tx as $va){
					if($va['created_at'] == $count_info['tx_time'][$i] && $va['student_id'] == $v['id']){
						$v['tx_'.$i] = $va['dictation_score'];
						break;
					}
				}
			}
			for($i=0;$i<$count_info['cs'];$i++){
				$v['cs_'.$i] = "";
				foreach($cs as $va){
					if($va['created_at'] == $count_info['cs_time'][$i] && $va['student_id'] == $v['id']){
						$v['cs_'.$i] = $va['test_score'];
						break;
					}
				}
			}
			for($i=0;$i<$count_info['kq'];$i++){
				$v['kq_'.$i] = "";
				foreach($kq as $va){
					if($va['created_at'] == $count_info['kq_time'][$i] && $va['student_id'] == $v['id']){
						$v['kq_'.$i] = $va['attendance_status'];
						break;
					}
				}
			}
			for($i=0;$i<$count_info['jx'];$i++){
				$v['jx_'.$i] = "";
				foreach($jx as $va){
					if($va['created_at'] == $count_info['jx_time'][$i] && $va['student_id'] == $v['id']){
						$v['jx_'.$i] = $va['jiaxiao_score'];
						break;
					}
				}
			}
			for($i=0;$i<$count_info['zy'];$i++){
				$v['zy_'.$i] = "";
				foreach($zy as $va){
					if($va['created_at'] == $count_info['zy_time'][$i] && $va['student_id'] == $v['id']){
						$v['zy_'.$i] = $va['zuoye_score'];
						break;
					}
				}
			}
		}
		return ['code'=>1,'msg'=>'加载成功','rows' => $rows];
	}
}
